﻿using Entity.Models;
using HuaRunInterface.Comm;
using HuaRunInterface.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Utility;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaRunInterface.Controllers.RollbackControllers
{
    [Route("rtu")]
    [ApiController]
    public class RtuRollbackController : ControllerBase
    {
        // POST api/<RtuRollbackController>
        [HttpPost]
        public object Post([FromBody] ReqRTURollbackModel value)
        {
            return UpdateData(value);
        }

        private object UpdateData(ReqRTURollbackModel dto)
        {
            ReturnRollbackModel rd = new ReturnRollbackModel();
            Utility.WriteLog.WriteLogFile($"rtu rollback :{dto.SerializerObjectToString()}");
            try
            {
                string conn = Global.Configuration["ConnectionStrings:DDb"];
                using (Entity.DBContext context = Entity.BaseContext.CreateContext(conn))
                {
                    RTUInfo v = context.rTUInfos.Where(p => p.deviceCode == dto.deviceCode && p.IsDelete != 1).FirstOrDefault();
                    if (v == null)
                    {
                        rd.code = 500;
                        rd.msg = "设备信息没有找到";
                    }
                    else
                    {
                        v.IsDelete = (dto.opType == 1 ? 1 : 0);
                        v.IsStatus = dto.status;
                        v.ResultMsg = dto.resultMsg;
                        v.RegisterDate = dto.opType == 0 ? DateTime.Now : null;
                        v.DeleteDate = dto.opType == 1 ? DateTime.Now : null;
                        v.uniqueDeviceIdentifier = dto.uniqueDeviceIdentifier;

                        context.rTUInfos.Update(v);
                        rd.code = context.SaveChanges() > 0 ? 200 : 500;
                    }
                }
            }
            catch (Exception ex)
            {
                rd.msg = ex.Message;
                rd.code = 500;
            }
            return rd;
        }
    }

    public class ReqRTURollbackModel
    {
        public string? sequence { get; set; }//String  Y 业务序列
        public string? domainId { get; set; }//String  Y 公司id
        public string? deviceCode { get; set; }//String  N 设备编码
        public int? opType { get; set; }//Integer Y 操作类型：0注册、1删除
        public int? status { get; set; }// Integer Y   操作状态：0失败、1成功
        public string? resultMsg { get; set; }//String Y   结果描述
        public string? uniqueDeviceIdentifier { get; set; }//String Y   设备唯一标示符，注册成功时返回
    }
}
